package com.to8to.kitt;

import org.apache.thrift.TApplicationException;
import org.apache.thrift.TBase;
import org.apache.thrift.protocol.TMessage;
import org.apache.thrift.protocol.TMessageMeta;
import org.apache.thrift.protocol.TMessageType;

public class ThriftMessage {

	private TMessage head; // meta info of thrift message
	
	private TMessageMeta meta;

	private TBase<?, ?> body; // user defined thrift object
	
	private TApplicationException exception; // thrift exception

	public ThriftMessage() {

	}

	public ThriftMessage(TMessage meta) {
		this.head = meta;
	}

	public ThriftMessage(TMessage meta, TBase<?, ?> body) {
		this.head = meta;
		this.body = body;
	}

	public ThriftMessage(TMessage meta, TApplicationException e) {
		this.head = meta;
		this.exception = e;
	}

	public static ThriftMessage newReplyMessage(TMessage head) {
		TMessage newHead = new TMessage(head.name, TMessageType.REPLY, head.seqid);
		return new ThriftMessage(newHead);
	}

	public TMessageMeta getMeta() {
		if(meta == null)
			meta = new TMessageMeta(head.name);
		return meta;
	}

	public void setMeta(TMessageMeta meta) {
		this.meta = meta;
	}

	public byte getType() {
		if (head == null)
			return 0;
		return head.type;
	}


	public TMessage getHead() {
		return head;
	}

	public void setHead(TMessage head) {
		this.head = head;
	}

	public TBase<?, ?> getBody() {
		return body;
	}

	public void setBody(TBase<?, ?> body) {
		this.body = body;
	}

	public TApplicationException getException() {
		return exception;
	}

	public void setException(TApplicationException exception) {
		this.exception = exception;
	}

	public void setSeqid(int seqid) {
		this.head = new TMessage(head.name, head.type, seqid);
	}

	public int getSeqid() {
		return head.seqid;
	}

	public boolean isCall() {
		return head.type == TMessageType.CALL;
	}

	public boolean isReply() {
		return head.type == TMessageType.REPLY;
	}

	public boolean isException() {
		return head.type == TMessageType.EXCEPTION;
	}

	public String toString() {
		return "{ \"head\" : " + head + ", \"body\" : " + body + ", \"exception\" : " + exception + "}";
	}
}
